package org.example.k8s_cloudplatform.K8S_mapper;

import io.kubernetes.client.custom.IntOrString;
import io.kubernetes.client.openapi.ApiException;
import io.kubernetes.client.openapi.apis.CoreV1Api;
import io.kubernetes.client.openapi.models.*;
import org.example.k8s_cloudplatform.entity.Pod;
import org.example.k8s_cloudplatform.utils.K8S_util;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public class ServiceMapper {

    private final CoreV1Api coreApi= K8S_util.coreApi;

    public V1Service createByPod(Pod pod) throws ApiException {
        V1Service res;
        V1Service service = new V1Service();

        V1ObjectMeta metadata = new V1ObjectMeta();
        metadata.setName("ssh-service-"+pod.getUserID()+"-"+pod.getName());
        service.setMetadata(metadata);

        V1ServiceSpec serviceSpec = new V1ServiceSpec();

        serviceSpec.setType("NodePort");

        V1ServicePort servicePort = new V1ServicePort();
        servicePort.setTargetPort(new IntOrString(22));
        servicePort.setPort(22);
        List<V1ServicePort> ports=new ArrayList<>();
        ports.add(servicePort);
        serviceSpec.setPorts(ports);

        Map<String, String> labels = new HashMap<>();
        labels.put("userID",pod.getUserID()+"");
        labels.put("name",pod.getName());
        serviceSpec.setSelector(labels);

        service.setSpec(serviceSpec);

        res=coreApi.createNamespacedService(pod.getUserID()+"",service,null,null,null);

        return res;
    }

    public V1Status delete(Pod pod) throws ApiException{
        // 创建删除选项
        V1DeleteOptions deleteOptions = new V1DeleteOptions();
        deleteOptions.setPropagationPolicy("Foreground");
        //删除pod
        return coreApi.deleteNamespacedService("ssh-service-"+pod.getUserID()+"-"+pod.getName(), pod.getUserID().toString(), null, null,
                null, null, null,deleteOptions);
    }
}
